<?php
namespace Lib;
class Json {
	public function encode($aValue) {
		return json_encode ( $aValue );
	}
	
	public function decode($sString, $bIsArray = true) {
		return json_decode ( $sString, $bIsArray );
	}
	
	public function format($sJsonString) {
		if (is_array ( $sJsonString )) {
			$sJsonString = json_encode ( $sJsonString );
		}
		$iLength = strlen ( $sJsonString );
		$bHaveQuota = false;
		$iTab = 0;
		$sFormatString = '';
		for($i = 0; $i < $iLength; $i ++) {
			$c = $sJsonString {$i};
			if ($bHaveQuota == false) {
				if ($c == '{') {
					$sFormatString = trim ( $sFormatString );
					$sFormatString .= $c . "\n" . str_repeat ( "\t", ++ $iTab );
				} elseif ($c == '}') {
					$iTab -= 1;
					$sFormatString .= "\n" . str_repeat ( "\t", $iTab ) . $c . "\n" . str_repeat ( "\t", $iTab );
				} elseif ($c == ',' || $c == ']') {
					$sFormatString = trim ( $sFormatString );
					$sFormatString .= $c . "\n" . str_repeat ( "\t", $iTab );
				} elseif ($c == ':') {
					$sFormatString .= $c . " ";
				} else {
					$sFormatString .= $c;
				}
			} elseif ($c == '"') {
				$bHaveQuota = ! $bHaveQuota;
				$sFormatString .= $c;
			} else {
				$sFormatString .= $c;
			}
		
		}
		return trim ( $sFormatString );
	}
}